package com.qianfeng.zhangwei.day46.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * @说 明：
 * @项目名称：1506adc
 * @包 名： com.qianfeng.zhangwei.day39
 * @类 名：TabVpiAdapter
 * @创 建人：zhangwei
 * @创建时间：2015-06-30 16 : 25
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class TabVpiAdapter extends PagerAdapter {
    private List<Fragment> fragmentList;
    private FragmentManager fragmentManager;

    private String[] titles;

    public TabVpiAdapter(List<Fragment> fragmentList, FragmentManager manager, String[] titles) {
        this.fragmentList = fragmentList;
        this.fragmentManager = manager;
        this.titles = titles;
    }


    @Override
    public int getCount() {
        return fragmentList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = fragmentList.get(position);
        if (!fragment.isAdded()) {
            fragmentManager.beginTransaction().add(fragment, fragment.getClass().getName()).commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        View view = fragment.getView();
        if (view.getParent() == null) {
            container.addView(view);
        }
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(fragmentList.get(position).getView());
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles != null && titles.length > 0 ? titles[position] : super.getPageTitle(position);
    }
}
